import axios from 'axios'
import router from '@/router/routers'
import { Notification, Loading } from 'element-ui'
import store from '../store'
import { getToken, removeToken } from '@/utils/auth'
import Config from '@/settings'
import MiddleUtil from '@/utils/MiddleUtil'

let loading = null
let reqNum = 0
let requestConfig = null

function startLoading() {
  if (reqNum === 0) {
    loading = Loading.service({
      lock: true,
      text: '加载中……',
      background: 'rgba(0, 0, 0, 0.6)'
    })
  }
  reqNum++
}
function endLoading() {
  if (reqNum <= 0) return
  reqNum--
  if (reqNum === 0) {
    loading.close()
  }
}

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? window.location.origin + '/api' : process.env.VUE_APP_BASE_API + '/api',
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    requestConfig = config
    if (config.url.includes('/oauth/token')) {
      config.headers['Captcha-Key'] = sessionStorage.getItem('codeKey')
      config.headers['Captcha-Code'] = sessionStorage.getItem('userInputCode')
    }
    // startLoading()
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    if (config.url.includes('/oauth/captcha') || config.url.includes('/oauth/token')) {
      config.headers['Authorization'] = ' '
    }
    config.headers['Content-Type'] = 'application/json;charset=UTF-8' // 'application/x-www-form-urlencoded'
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.config.url.includes('authmanage/exportSignXml')) {
      return response
    } else {
      return response.data
    }
    // endLoading()
    // return response.data
  },
  error => {
    console.log(error)
    // endLoading()
    MiddleUtil.$emit('closeLoading')
    MiddleUtil.$emit('requestError')// 用来关闭页面操作请求的loading
    if (requestConfig.url.includes('getUserMenus')) {
      removeToken()
      router.push({ path: '/login?t' + Math.random() })
    }
    const response = JSON.parse(JSON.stringify(error)).response

    if (response && response.config.url.includes('/apiInfo/send')) {
      return response.data
    }

    if (response && response.data && response.data.code != '200') {
      if (!response || response.data.code == '401') {
        Notification.error({
          title: 'token失效，请重新登录',
          duration: 2000
        })
        removeToken()

        router.push({ path: '/login?t' + Math.random() })
      } else {
        Notification.error({
          title: response.data.msg || response.data.error_description || '接口报错',
          duration: 5000
        })
      }
    }
    return Promise.reject(response)
  }
)
export default service
